package VideoProcessing;

import java.awt.Dimension;
import java.awt.image.WritableRaster;

import javax.media.format.VideoFormat;

public class ErosionEffect extends RgbVideoEffect {
	private static final int N = 9;
	private static final int[] OX = { 0, -1, 0, 1, 1, 1, 0, -1, -1 };
	private static final int[] OY = { 0, -1, -1, -1, 0, 1, 1, 1, 0 };
	private Dimension size;

	@Override
	protected boolean processRGB(byte[] bin, byte[] bout, VideoFormat format) {
		size = format.getSize();
		for (int y = 0; y < size.height; y++) {
			for (int x = 0; x < size.width; x++) {
				boolean erosion = false;
				for (int k = 0; k < N; k++) {
					int tx, ty;
					tx = x + OX[k];
					ty = y + OY[k];
					if (inBoundry(tx, ty, size.width, size.width)
							&& bin[(ty * size.width + tx)] == 0) {
						erosion = true;
						break;
					}
				}
				if (erosion) {
					bout[(y * size.width + x)] = 0;
				} else {
					bout[(y * size.width + x)] = 1;
				}
			}
		}
		return true;
	}

	private boolean inBoundry(int tx, int ty, int width, int width2) {
		return (0 <= tx && tx < size.width) && (0 <= ty && ty < size.height);
	}

	@Override
	public String getName() {
		return "Dilation";
	}
	protected void updateImage(byte[] bout, VideoFormat vformat) {
		synchronized (displayImage) {
			// // Copy pixels to image
			WritableRaster rast = displayImage.getRaster();
			int[] pixel = new int[] { 0, 0, 0, 255 };
			int p = 0;
			for (int y = vformat.getSize().height - 1; y >= 0; y--) {
				for (int x = 0; x < vformat.getSize().width; x++) {
					pixel[0] = pixel[1] = pixel[2] = bout[p++];
					rast.setPixel(x, y, pixel);
				}
			}
		}
	}

}
